package cn.cimoc.security;

import cn.cimoc.mapper.AdminMapper;
import cn.cimoc.vo.AdminLoginVO;
import cn.cimoc.vo.PermissionVO;
import cn.cimoc.security.pojo.UserUserDetails;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private AdminMapper adminMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        AdminLoginVO admin = adminMapper.getLoginInfoByUsername(username);
        if(admin == null){
           return null; //不在 spring Security内部来处理异常(它重定向到自己的/login请求)，该异常由程序员自行处理
        }

        //以下是处理授权的代码
        List<PermissionVO> permissions = admin.getPermissions();
        log.info("此用户的权限信息：{}",permissions);
        //将用户的权限信息转换为Spring Security要求的List<GrantedAuthority>类型的数据
        List<SimpleGrantedAuthority> authorities = new ArrayList<SimpleGrantedAuthority>();
        for(PermissionVO permission:permissions){
            String permissionValue = permission.getValue();
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority(permissionValue);
            authorities.add(authority);
        }
        //构造UserDetails对象
//      .accountExpired(false) 账号是否过期
//      .accountLocked(false)  账号是否锁定
//      .credentialsExpired(false)  证书是否过期
//        return User.builder()
//                .username(admin.getUsername())
//                .password(admin.getPassword())
//                .disabled(admin.getIsEnable() == 0)
//                .accountExpired(false)
//                .accountLocked(false)
//                .credentialsExpired(false)
//                .authorities(authorities)
//                .build();

        //下面使用 自定义UserUserDetails来封装数据，这样就不会默认将userDetails保存在session中
        UserUserDetails userDetails = new UserUserDetails();
        userDetails.setId(admin.getId());
        userDetails.setUsername(admin.getUsername());
        userDetails.setPassword(admin.getPassword());
        userDetails.setAuthorities(authorities);
        return userDetails;
    }
}
